<?php
namespace app\common\services;

use support\Redis;
use support\Log;
use support\Db;

/**
 * 反欺诈服务
 * 检测和防止设备欺诈、刷量、模拟器等恶意行为
 */
class AntiFraudService
{
    /**
     * 风险评分阈值
     */
    const RISK_THRESHOLD_HIGH = 80;
    const RISK_THRESHOLD_MEDIUM = 50;
    const RISK_THRESHOLD_LOW = 20;
    
    /**
     * 限制配置
     */
    const MAX_REQUESTS_PER_IP = 100; // 每小时每IP最大请求数
    const MAX_REQUESTS_PER_DEVICE = 50; // 每小时每设备最大请求数
    const MAX_INSTALLS_PER_IP = 10; // 每小时每IP最大安装数
    const SUSPICIOUS_TIME_RANGE = 300; // 可疑时间范围（秒）
    
    /**
     * 检测类型
     */
    const DETECTION_TYPES = [
        'emulator' => '模拟器检测',
        'vpn_proxy' => 'VPN/代理检测',
        'bot' => '机器人检测',
        'farm' => '设备农场检测',
        'injection' => '参数注入检测',
        'replay' => '重放攻击检测'
    ];

    /**
     * 检查设备欺诈
     */
    public function checkDeviceFraud($deviceInfo, $fingerprint)
    {
        $riskScore = 0;
        $riskReasons = [];
        $detectionResults = [];
        
        // 1. 基础信息验证
        $basicCheck = $this->checkBasicInfo($deviceInfo);
        if (!$basicCheck['valid']) {
            $riskScore += 30;
            $riskReasons[] = $basicCheck['reason'];
            $detectionResults['basic_info'] = $basicCheck;
        }
        
        // 2. 模拟器检测
        $emulatorCheck = $this->detectEmulator($deviceInfo);
        if ($emulatorCheck['is_emulator']) {
            $riskScore += 40;
            $riskReasons[] = 'Device appears to be an emulator';
            $detectionResults['emulator'] = $emulatorCheck;
        }
        
        // 3. VPN/代理检测
        $vpnCheck = $this->detectVPNProxy();
        if ($vpnCheck['is_vpn']) {
            $riskScore += 25;
            $riskReasons[] = 'VPN/Proxy detected';
            $detectionResults['vpn_proxy'] = $vpnCheck;
        }
        
        // 4. 机器人检测
        $botCheck = $this->detectBot($deviceInfo);
        if ($botCheck['is_bot']) {
            $riskScore += 35;
            $riskReasons[] = 'Bot behavior detected';
            $detectionResults['bot'] = $botCheck;
        }
        
        // 5. 设备农场检测
        $farmCheck = $this->detectDeviceFarm($deviceInfo, $fingerprint);
        if ($farmCheck['is_farm']) {
            $riskScore += 50;
            $riskReasons[] = 'Device farm detected';
            $detectionResults['device_farm'] = $farmCheck;
        }
        
        // 6. 频率限制检查
        $rateLimitCheck = $this->checkRateLimit($deviceInfo, $fingerprint);
        if (!$rateLimitCheck['allowed']) {
            $riskScore += 20;
            $riskReasons[] = 'Rate limit exceeded';
            $detectionResults['rate_limit'] = $rateLimitCheck;
        }
        
        // 7. 参数注入检测
        $injectionCheck = $this->detectParameterInjection($deviceInfo);
        if ($injectionCheck['has_injection']) {
            $riskScore += 30;
            $riskReasons[] = 'Parameter injection detected';
            $detectionResults['injection'] = $injectionCheck;
        }
        
        // 8. 重放攻击检测
        $replayCheck = $this->detectReplayAttack($deviceInfo, $fingerprint);
        if ($replayCheck['is_replay']) {
            $riskScore += 25;
            $riskReasons[] = 'Replay attack detected';
            $detectionResults['replay'] = $replayCheck;
        }
        
        // 9. 设备指纹一致性检查
        $fingerprintCheck = $this->checkFingerprintConsistency($deviceInfo, $fingerprint);
        if (!$fingerprintCheck['consistent']) {
            $riskScore += 15;
            $riskReasons[] = 'Fingerprint inconsistency detected';
            $detectionResults['fingerprint'] = $fingerprintCheck;
        }
        
        // 10. 地理位置异常检测
        $geoCheck = $this->detectGeoAnomaly($deviceInfo);
        if ($geoCheck['is_anomaly']) {
            $riskScore += 20;
            $riskReasons[] = 'Geographic anomaly detected';
            $detectionResults['geo_anomaly'] = $geoCheck;
        }
        
        // 确定风险等级
        $riskLevel = $this->determineRiskLevel($riskScore);
        
        // 记录检测结果
        $this->logDetectionResult($deviceInfo, $fingerprint, $riskScore, $riskLevel, $detectionResults);
        
        // 决定是否允许
        $allowed = $riskLevel !== 'high';
        
        return [
            'allowed' => $allowed,
            'risk_score' => $riskScore,
            'risk_level' => $riskLevel,
            'reason' => implode('; ', $riskReasons) ?: 'Device passed all checks',
            'detection_results' => $detectionResults,
            'recommendations' => $this->getRecommendations($riskLevel, $detectionResults)
        ];
    }

    /**
     * 基础信息验证
     */
    private function checkBasicInfo($deviceInfo)
    {
        $issues = [];
        
        // 检查必需字段
        $requiredFields = ['platform', 'device_model', 'os_version'];
        foreach ($requiredFields as $field) {
            if (empty($deviceInfo[$field])) {
                $issues[] = "Missing required field: {$field}";
            }
        }
        
        // 检查字段格式
        if (!empty($deviceInfo['platform'])) {
            $validPlatforms = ['ios', 'android', 'windows', 'macos', 'linux', 'web'];
            if (!in_array(strtolower($deviceInfo['platform']), $validPlatforms)) {
                $issues[] = 'Invalid platform value';
            }
        }
        
        // 检查版本号格式
        if (!empty($deviceInfo['os_version'])) {
            if (!preg_match('/^\d+(\.\d+)*$/', $deviceInfo['os_version'])) {
                $issues[] = 'Invalid OS version format';
            }
        }
        
        // 检查屏幕分辨率
        if (!empty($deviceInfo['screen_resolution'])) {
            if (!preg_match('/^\d+x\d+$/', $deviceInfo['screen_resolution'])) {
                $issues[] = 'Invalid screen resolution format';
            }
        }
        
        return [
            'valid' => empty($issues),
            'reason' => empty($issues) ? '' : 'Basic info validation failed: ' . implode(', ', $issues),
            'issues' => $issues
        ];
    }

    /**
     * 模拟器检测
     */
    private function detectEmulator($deviceInfo)
    {
        $emulatorIndicators = [];
        $suspiciousPatterns = [
            'device_model' => ['/emulator/i', '/sdk/i', '/google/i', '/unknown/i'],
            'manufacturer' => ['/unknown/i', '/generic/i', '/sdk/i'],
            'hardware' => ['/goldfish/i', '/ranchu/i', '/qemu/i'],
            'board' => ['/goldfish/i', '/ranchu/i'],
            'bootloader' => ['/unknown/i'],
            'device_id' => ['/000000000000000/i', '/0123456789abcdef/i']
        ];
        
        foreach ($suspiciousPatterns as $field => $patterns) {
            if (!empty($deviceInfo[$field])) {
                foreach ($patterns as $pattern) {
                    if (preg_match($pattern, $deviceInfo[$field])) {
                        $emulatorIndicators[] = [
                            'field' => $field,
                            'value' => $deviceInfo[$field],
                            'pattern' => $pattern
                        ];
                    }
                }
            }
        }
        
        // 检查不真实的硬件配置
        if (isset($deviceInfo['cpu_cores']) && $deviceInfo['cpu_cores'] > 16) {
            $emulatorIndicators[] = [
                'field' => 'cpu_cores',
                'value' => $deviceInfo['cpu_cores'],
                'reason' => 'Unrealistic CPU core count'
            ];
        }
        
        if (isset($deviceInfo['memory']) && $deviceInfo['memory'] > 64000) {
            $emulatorIndicators[] = [
                'field' => 'memory',
                'value' => $deviceInfo['memory'],
                'reason' => 'Unrealistic memory size'
            ];
        }
        
        // 检查传感器信息
        if (isset($deviceInfo['sensors'])) {
            $sensorCount = count($deviceInfo['sensors']);
            if ($sensorCount < 3) {
                $emulatorIndicators[] = [
                    'field' => 'sensors',
                    'value' => $sensorCount,
                    'reason' => 'Too few sensors'
                ];
            }
        }
        
        $isEmulator = count($emulatorIndicators) >= 2;
        
        return [
            'is_emulator' => $isEmulator,
            'confidence' => min(count($emulatorIndicators) * 0.3, 1.0),
            'indicators' => $emulatorIndicators
        ];
    }

    /**
     * VPN/代理检测
     */
    private function detectVPNProxy()
    {
        $indicators = [];
        $clientIp = $this->getClientIp();
        
        // 检查HTTP头
        $proxyHeaders = [
            'HTTP_VIA',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'HTTP_PROXY_CONNECTION'
        ];
        
        foreach ($proxyHeaders as $header) {
            if (!empty($_SERVER[$header])) {
                $indicators[] = [
                    'type' => 'proxy_header',
                    'header' => $header,
                    'value' => $_SERVER[$header]
                ];
            }
        }
        
        // 检查常见VPN端口
        $commonVPNPorts = [1194, 1723, 500, 1701, 4500];
        $remotePort = intval($_SERVER['REMOTE_PORT'] ?? 0);
        if (in_array($remotePort, $commonVPNPorts)) {
            $indicators[] = [
                'type' => 'vpn_port',
                'port' => $remotePort
            ];
        }
        
        // 检查IP地址类型
        if ($this->isVpnIpRange($clientIp)) {
            $indicators[] = [
                'type' => 'vpn_ip_range',
                'ip' => $clientIp
            ];
        }
        
        // 检查数据中心IP
        if ($this->isDataCenterIp($clientIp)) {
            $indicators[] = [
                'type' => 'data_center_ip',
                'ip' => $clientIp
            ];
        }
        
        $isVpn = count($indicators) >= 2;
        
        return [
            'is_vpn' => $isVpn,
            'confidence' => min(count($indicators) * 0.25, 1.0),
            'indicators' => $indicators
        ];
    }

    /**
     * 机器人检测
     */
    private function detectBot($deviceInfo)
    {
        $botIndicators = [];
        
        // User Agent检测
        $userAgent = $deviceInfo['user_agent'] ?? '';
        $botPatterns = [
            '/bot/i', '/spider/i', '/crawler/i', '/scraper/i', '/curl/i',
            '/wget/i', '/python/i', '/java/i', '/phantom/i', '/headless/i',
            '/selenium/i', '/webdriver/i', '/puppeteer/i', '/playwright/i'
        ];
        
        foreach ($botPatterns as $pattern) {
            if (preg_match($pattern, $userAgent)) {
                $botIndicators[] = [
                    'type' => 'user_agent',
                    'pattern' => $pattern,
                    'user_agent' => $userAgent
                ];
            }
        }
        
        // 行为模式检测
        if (isset($deviceInfo['behavior_metrics'])) {
            $metrics = $deviceInfo['behavior_metrics'];
            
            // 检查鼠标移动模式
            if (isset($metrics['mouse_movements'])) {
                $movements = $metrics['mouse_movements'];
                if (count($movements) < 5) {
                    $botIndicators[] = [
                        'type' => 'mouse_movements',
                        'reason' => 'Too few mouse movements',
                        'count' => count($movements)
                    ];
                }
                
                // 检查移动模式是否过于规律
                if ($this->isRegularPattern($movements)) {
                    $botIndicators[] = [
                        'type' => 'mouse_pattern',
                        'reason' => 'Regular mouse movement pattern'
                    ];
                }
            }
            
            // 检查键盘输入模式
            if (isset($metrics['keyboard_events'])) {
                $keyboardEvents = $metrics['keyboard_events'];
                if (count($keyboardEvents) === 0) {
                    $botIndicators[] = [
                        'type' => 'keyboard_events',
                        'reason' => 'No keyboard events',
                        'count' => 0
                    ];
                }
            }
            
            // 检查页面停留时间
            if (isset($metrics['page_time'])) {
                $pageTime = $metrics['page_time'];
                if ($pageTime < 1000) { // 小于1秒
                    $botIndicators[] = [
                        'type' => 'page_time',
                        'reason' => 'Too short page time',
                        'time' => $pageTime
                    ];
                }
            }
        }
        
        // 检查请求频率
        $requestFrequency = $this->getRequestFrequency();
        if ($requestFrequency > 10) { // 每秒超过10个请求
            $botIndicators[] = [
                'type' => 'request_frequency',
                'reason' => 'High request frequency',
                'frequency' => $requestFrequency
            ];
        }
        
        $isBot = count($botIndicators) >= 2;
        
        return [
            'is_bot' => $isBot,
            'confidence' => min(count($botIndicators) * 0.3, 1.0),
            'indicators' => $botIndicators
        ];
    }

    /**
     * 设备农场检测
     */
    private function detectDeviceFarm($deviceInfo, $fingerprint)
    {
        $farmIndicators = [];
        $clientIp = $this->getClientIp();
        
        // 检查同一IP下的设备数量
        $devicesPerIp = $this->getDevicesCountByIp($clientIp);
        if ($devicesPerIp > 20) {
            $farmIndicators[] = [
                'type' => 'devices_per_ip',
                'count' => $devicesPerIp,
                'threshold' => 20
            ];
        }
        
        // 检查设备相似度
        $similarDevices = $this->getSimilarDevices($deviceInfo, $fingerprint);
        if ($similarDevices > 10) {
            $farmIndicators[] = [
                'type' => 'similar_devices',
                'count' => $similarDevices,
                'threshold' => 10
            ];
        }
        
        // 检查设备指纹相似度
        $fingerprintSimilarity = $this->checkFingerprintSimilarity($fingerprint);
        if ($fingerprintSimilarity > 0.9) {
            $farmIndicators[] = [
                'type' => 'fingerprint_similarity',
                'similarity' => $fingerprintSimilarity,
                'threshold' => 0.9
            ];
        }
        
        // 检查时间模式
        $timePattern = $this->analyzeTimePattern($clientIp);
        if ($timePattern['is_suspicious']) {
            $farmIndicators[] = [
                'type' => 'time_pattern',
                'pattern' => $timePattern['pattern'],
                'reason' => $timePattern['reason']
            ];
        }
        
        // 检查硬件配置相似度
        $hardwareSimilarity = $this->checkHardwareSimilarity($deviceInfo);
        if ($hardwareSimilarity > 0.85) {
            $farmIndicators[] = [
                'type' => 'hardware_similarity',
                'similarity' => $hardwareSimilarity,
                'threshold' => 0.85
            ];
        }
        
        $isFarm = count($farmIndicators) >= 2;
        
        return [
            'is_farm' => $isFarm,
            'confidence' => min(count($farmIndicators) * 0.25, 1.0),
            'indicators' => $farmIndicators
        ];
    }

    /**
     * 频率限制检查
     */
    private function checkRateLimit($deviceInfo, $fingerprint)
    {
        $clientIp = $this->getClientIp();
        $currentTime = time();
        $timeWindow = 3600; // 1小时
        
        // IP级别限制
        $ipKey = "rate_limit:ip:{$clientIp}";
        $ipRequests = Redis::get($ipKey) ?: 0;
        
        if ($ipRequests >= self::MAX_REQUESTS_PER_IP) {
            return [
                'allowed' => false,
                'reason' => 'IP rate limit exceeded',
                'limit' => self::MAX_REQUESTS_PER_IP,
                'current' => $ipRequests,
                'level' => 'ip'
            ];
        }
        
        // 设备级别限制
        $deviceKey = "rate_limit:device:{$fingerprint}";
        $deviceRequests = Redis::get($deviceKey) ?: 0;
        
        if ($deviceRequests >= self::MAX_REQUESTS_PER_DEVICE) {
            return [
                'allowed' => false,
                'reason' => 'Device rate limit exceeded',
                'limit' => self::MAX_REQUESTS_PER_DEVICE,
                'current' => $deviceRequests,
                'level' => 'device'
            ];
        }
        
        // 安装频率限制
        $installKey = "rate_limit:install:{$clientIp}";
        $installCount = Redis::get($installKey) ?: 0;
        
        if ($installCount >= self::MAX_INSTALLS_PER_IP) {
            return [
                'allowed' => false,
                'reason' => 'Install rate limit exceeded',
                'limit' => self::MAX_INSTALLS_PER_IP,
                'current' => $installCount,
                'level' => 'install'
            ];
        }
        
        // 增加计数
        Redis::incr($ipKey);
        Redis::expire($ipKey, $timeWindow);
        
        Redis::incr($deviceKey);
        Redis::expire($deviceKey, $timeWindow);
        
        return [
            'allowed' => true,
            'reason' => 'Rate limit check passed',
            'ip_requests' => $ipRequests + 1,
            'device_requests' => $deviceRequests + 1
        ];
    }

    /**
     * 参数注入检测
     */
    private function detectParameterInjection($deviceInfo)
    {
        $injectionIndicators = [];
        
        // SQL注入检测
        $sqlPatterns = [
            '/(\b(union|select|insert|update|delete|drop|create|alter|exec|script|declare|cast|convert)\b)/i',
            '/(--|\/\*|\*\/|\\x00|\\x1a|\\x08|\\x09|\\x0a|\\x0d|\\x1f)/i',
            '/(\\x00|\\x08|\\x09|\\x0a|\\x0d|\\x1a|\\x20|\\x21|\\x22|\\x23|\\x25|\\x27|\\x28|\\x29|\\x2a|\\x2b|\\x2c|\\x2d|\\x2e|\\x2f|\\x3a|\\x3b|\\x3c|\\x3d|\\x3e|\\x3f|\\x5b|\\x5c|\\x5d|\\x5e|\\x5f|\\x60|\\x7b|\\x7c|\\x7d|\\x7e|\\x7f)/i'
        ];
        
        foreach ($deviceInfo as $key => $value) {
            if (is_string($value)) {
                foreach ($sqlPatterns as $pattern) {
                    if (preg_match($pattern, $value)) {
                        $injectionIndicators[] = [
                            'type' => 'sql_injection',
                            'field' => $key,
                            'pattern' => $pattern,
                            'value' => substr($value, 0, 100) // 限制长度
                        ];
                    }
                }
            }
        }
        
        // XSS检测
        $xssPatterns = [
            '/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/i',
            '/javascript:/i',
            '/on\w+\s*=/i',
            '/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/i',
            '/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/i',
            '/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/i',
            '/<form\b[^<]*(?:(?!<\/form>)<[^<]*)*<\/form>/i'
        ];
        
        foreach ($deviceInfo as $key => $value) {
            if (is_string($value)) {
                foreach ($xssPatterns as $pattern) {
                    if (preg_match($pattern, $value)) {
                        $injectionIndicators[] = [
                            'type' => 'xss_injection',
                            'field' => $key,
                            'pattern' => $pattern,
                            'value' => substr($value, 0, 100)
                        ];
                    }
                }
            }
        }
        
        // 命令注入检测
        $commandPatterns = [
            '/[;&|`]/',
            '/\$\(/',
            '/\\x60/',
            '/(nc|netcat|wget|curl|python|perl|ruby|bash|sh|cmd|powershell)/i'
        ];
        
        foreach ($deviceInfo as $key => $value) {
            if (is_string($value)) {
                foreach ($commandPatterns as $pattern) {
                    if (preg_match($pattern, $value)) {
                        $injectionIndicators[] = [
                            'type' => 'command_injection',
                            'field' => $key,
                            'pattern' => $pattern,
                            'value' => substr($value, 0, 100)
                        ];
                    }
                }
            }
        }
        
        $hasInjection = count($injectionIndicators) > 0;
        
        return [
            'has_injection' => $hasInjection,
            'confidence' => min(count($injectionIndicators) * 0.3, 1.0),
            'indicators' => $injectionIndicators
        ];
    }

    /**
     * 重放攻击检测
     */
    private function detectReplayAttack($deviceInfo, $fingerprint)
    {
        $replayIndicators = [];
        $clientIp = $this->getClientIp();
        
        // 检查重复的设备指纹
        $fingerprintKey = "replay:fingerprint:{$fingerprint}";
        $existingFingerprint = Redis::get($fingerprintKey);
        
        if ($existingFingerprint) {
            $existingData = json_decode($existingFingerprint, true);
            $timeDiff = time() - $existingData['timestamp'];
            
            if ($timeDiff < self::SUSPICIOUS_TIME_RANGE) {
                $replayIndicators[] = [
                    'type' => 'duplicate_fingerprint',
                    'time_diff' => $timeDiff,
                    'threshold' => self::SUSPICIOUS_TIME_RANGE
                ];
            }
        }
        
        // 检查重复的参数组合
        $paramHash = md5(json_encode($deviceInfo));
        $paramKey = "replay:params:{$paramHash}";
        $existingParams = Redis::get($paramKey);
        
        if ($existingParams) {
            $existingData = json_decode($existingParams, true);
            $timeDiff = time() - $existingData['timestamp'];
            
            if ($timeDiff < self::SUSPICIOUS_TIME_RANGE) {
                $replayIndicators[] = [
                    'type' => 'duplicate_params',
                    'time_diff' => $timeDiff,
                    'threshold' => self::SUSPICIOUS_TIME_RANGE
                ];
            }
        }
        
        // 检查时间戳异常
        if (isset($deviceInfo['client_timestamp'])) {
            $clientTime = intval($deviceInfo['client_timestamp']);
            $serverTime = time();
            $timeDiff = abs($serverTime - $clientTime);
            
            if ($timeDiff > 300) { // 5分钟差异
                $replayIndicators[] = [
                    'type' => 'timestamp_anomaly',
                    'client_time' => $clientTime,
                    'server_time' => $serverTime,
                    'diff' => $timeDiff,
                    'threshold' => 300
                ];
            }
        }
        
        // 记录当前请求
        $requestData = [
            'fingerprint' => $fingerprint,
            'ip' => $clientIp,
            'timestamp' => time(),
            'params' => $paramHash
        ];
        
        Redis::setex($fingerprintKey, 3600, json_encode($requestData));
        Redis::setex($paramKey, 3600, json_encode($requestData));
        
        $isReplay = count($replayIndicators) >= 1;
        
        return [
            'is_replay' => $isReplay,
            'confidence' => min(count($replayIndicators) * 0.5, 1.0),
            'indicators' => $replayIndicators
        ];
    }

    /**
     * 设备指纹一致性检查
     */
    private function checkFingerprintConsistency($deviceInfo, $fingerprint)
    {
        $inconsistencies = [];
        
        // 检查平台一致性
        if (!empty($deviceInfo['platform']) && !empty($deviceInfo['user_agent'])) {
            $platform = strtolower($deviceInfo['platform']);
            $userAgent = strtolower($deviceInfo['user_agent']);
            
            if ($platform === 'ios' && strpos($userAgent, 'android') !== false) {
                $inconsistencies[] = 'Platform iOS but UserAgent contains Android';
            }
            
            if ($platform === 'android' && strpos($userAgent, 'iphone') !== false) {
                $inconsistencies[] = 'Platform Android but UserAgent contains iPhone';
            }
        }
        
        // 检查屏幕分辨率合理性
        if (!empty($deviceInfo['screen_resolution'])) {
            $resolution = $deviceInfo['screen_resolution'];
            if (preg_match('/^(\d+)x(\d+)$/', $resolution, $matches)) {
                $width = intval($matches[1]);
                $height = intval($matches[2]);
                
                if ($width < 320 || $height < 240) {
                    $inconsistencies[] = 'Unrealistic screen resolution too small';
                }
                
                if ($width > 8000 || $height > 8000) {
                    $inconsistencies[] = 'Unrealistic screen resolution too large';
                }
            }
        }
        
        // 检查设备ID格式
        if (!empty($deviceInfo['device_id'])) {
            $deviceId = $deviceInfo['device_id'];
            
            if (strlen($deviceId) < 5) {
                $inconsistencies[] = 'Device ID too short';
            }
            
            if (preg_match('/^[0]+$/', $deviceId)) {
                $inconsistencies[] = 'Device ID all zeros';
            }
            
            if (preg_match('/^[a-f0-9]{16}$/i', $deviceId)) {
                // 可能是有效的设备ID格式
            } else if (strlen($deviceId) < 10) {
                $inconsistencies[] = 'Device ID format suspicious';
            }
        }
        
        $isConsistent = count($inconsistencies) === 0;
        
        return [
            'consistent' => $isConsistent,
            'inconsistencies' => $inconsistencies,
            'confidence' => 1.0 - (count($inconsistencies) * 0.1)
        ];
    }

    /**
     * 地理位置异常检测
     */
    private function detectGeoAnomaly($deviceInfo)
    {
        $anomalies = [];
        $clientIp = $this->getClientIp();
        
        // 获取IP地理位置
        $ipLocation = $this->getIpLocation($clientIp);
        
        // 检查设备报告的地理位置与IP地理位置是否一致
        if (!empty($deviceInfo['location'])) {
            $deviceLocation = $deviceInfo['location'];
            
            if (!empty($ipLocation['country']) && !empty($deviceLocation['country'])) {
                if (strtolower($ipLocation['country']) !== strtolower($deviceLocation['country'])) {
                    $anomalies[] = [
                        'type' => 'country_mismatch',
                        'ip_country' => $ipLocation['country'],
                        'device_country' => $deviceLocation['country']
                    ];
                }
            }
            
            // 检查距离是否合理
            if (!empty($ipLocation['lat']) && !empty($ipLocation['lon']) && 
                !empty($deviceLocation['lat']) && !empty($deviceLocation['lon'])) {
                
                $distance = $this->calculateDistance(
                    $ipLocation['lat'], $ipLocation['lon'],
                    $deviceLocation['lat'], $deviceLocation['lon']
                );
                
                if ($distance > 1000) { // 超过1000公里
                    $anomalies[] = [
                        'type' => 'distance_anomaly',
                        'distance' => $distance,
                        'threshold' => 1000,
                        'ip_location' => $ipLocation,
                        'device_location' => $deviceLocation
                    ];
                }
            }
        }
        
        // 检查时区与地理位置是否一致
        if (!empty($deviceInfo['timezone']) && !empty($ipLocation['timezone'])) {
            $deviceTimezone = $deviceInfo['timezone'];
            $ipTimezone = $ipLocation['timezone'];
            
            if (abs(intval($deviceTimezone) - intval($ipTimezone)) > 3) {
                $anomalies[] = [
                    'type' => 'timezone_anomaly',
                    'device_timezone' => $deviceTimezone,
                    'ip_timezone' => $ipTimezone
                ];
            }
        }
        
        $isAnomaly = count($anomalies) >= 1;
        
        return [
            'is_anomaly' => $isAnomaly,
            'confidence' => min(count($anomalies) * 0.5, 1.0),
            'anomalies' => $anomalies,
            'ip_location' => $ipLocation
        ];
    }

    /**
     * 确定风险等级
     */
    private function determineRiskLevel($riskScore)
    {
        if ($riskScore >= self::RISK_THRESHOLD_HIGH) {
            return 'high';
        } elseif ($riskScore >= self::RISK_THRESHOLD_MEDIUM) {
            return 'medium';
        } elseif ($riskScore >= self::RISK_THRESHOLD_LOW) {
            return 'low';
        } else {
            return 'safe';
        }
    }

    /**
     * 获取建议
     */
    private function getRecommendations($riskLevel, $detectionResults)
    {
        $recommendations = [];
        
        switch ($riskLevel) {
            case 'high':
                $recommendations[] = 'Block device immediately';
                $recommendations[] = 'Flag for manual review';
                $recommendations[] = 'Consider IP blocking';
                break;
            case 'medium':
                $recommendations[] = 'Increase monitoring';
                $recommendations[] = 'Require additional verification';
                $recommendations[] = 'Limit request frequency';
                break;
            case 'low':
                $recommendations[] = 'Monitor device behavior';
                $recommendations[] = 'Log additional metrics';
                break;
            default:
                $recommendations[] = 'No special action required';
        }
        
        // 基于具体检测结果的建议
        if (isset($detectionResults['emulator']) && $detectionResults['emulator']['is_emulator']) {
            $recommendations[] = 'Consider requiring real device verification';
        }
        
        if (isset($detectionResults['vpn_proxy']) && $detectionResults['vpn_proxy']['is_vpn']) {
            $recommendations[] = 'Consider geo-blocking or additional verification';
        }
        
        if (isset($detectionResults['device_farm']) && $detectionResults['device_farm']['is_farm']) {
            $recommendations[] = 'Implement device uniqueness constraints';
        }
        
        return $recommendations;
    }

    /**
     * 记录检测结果
     */
    private function logDetectionResult($deviceInfo, $fingerprint, $riskScore, $riskLevel, $detectionResults)
    {
        $logData = [
            'timestamp' => date('Y-m-d H:i:s'),
            'fingerprint' => $fingerprint,
            'ip' => $this->getClientIp(),
            'user_agent' => $deviceInfo['user_agent'] ?? '',
            'platform' => $deviceInfo['platform'] ?? '',
            'device_model' => $deviceInfo['device_model'] ?? '',
            'risk_score' => $riskScore,
            'risk_level' => $riskLevel,
            'detection_results' => $detectionResults
        ];
        
        // 记录到日志文件
        Log::channel('antifraud')->info('Anti-fraud detection', $logData);
        
        // 高风险事件记录到数据库
        if ($riskLevel === 'high') {
            $this->logHighRiskEvent($logData);
        }
    }

    /**
     * 记录高风险事件
     */
    private function logHighRiskEvent($logData)
    {
        try {
            Db::table('gf_antifraud_high_risk')->insert([
                'fingerprint' => $logData['fingerprint'],
                'ip' => $logData['ip'],
                'risk_score' => $logData['risk_score'],
                'risk_level' => $logData['risk_level'],
                'detection_results' => json_encode($logData['detection_results']),
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to log high risk event: ' . $e->getMessage());
        }
    }

    // 辅助方法
    private function getClientIp()
    {
        $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'];
        foreach ($ipKeys as $key) {
            if (!empty($_SERVER[$key])) {
                $ips = explode(',', $_SERVER[$key]);
                return trim($ips[0]);
            }
        }
        return '0.0.0.0';
    }

    private function isVpnIpRange($ip)
    {
        // 简化的VPN IP范围检测
        // 实际实现中应该使用IP数据库
        $vpnRanges = [
            '10.0.0.0/8',
            '172.16.0.0/12',
            '192.168.0.0/16'
        ];
        
        foreach ($vpnRanges as $range) {
            if ($this->ipInRange($ip, $range)) {
                return true;
            }
        }
        
        return false;
    }

    private function isDataCenterIp($ip)
    {
        // 简化的数据中心IP检测
        // 实际实现中应该使用IP数据库
        return false;
    }

    private function ipInRange($ip, $range)
    {
        list($rangeIp, $netmask) = explode('/', $range);
        $rangeDecimal = ip2long($rangeIp);
        $ipDecimal = ip2long($ip);
        $wildcardDecimal = pow(2, (32 - $netmask)) - 1;
        $netmaskDecimal = ~$wildcardDecimal;
        
        return ($ipDecimal & $netmaskDecimal) == ($rangeDecimal & $netmaskDecimal);
    }

    private function isRegularPattern($data)
    {
        if (count($data) < 3) return false;
        
        // 简单的规律性检测
        $differences = [];
        for ($i = 1; $i < count($data); $i++) {
            $differences[] = abs($data[$i] - $data[$i-1]);
        }
        
        $variance = $this->calculateVariance($differences);
        return $variance < 0.1; // 方差很小表示很规律
    }

    private function calculateVariance($data)
    {
        if (count($data) === 0) return 0;
        
        $mean = array_sum($data) / count($data);
        $squaredDiffs = array_map(function($value) use ($mean) {
            return pow($value - $mean, 2);
        }, $data);
        
        return array_sum($squaredDiffs) / count($data);
    }

    private function getRequestFrequency()
    {
        // 简化的请求频率计算
        // 实际实现中应该基于时间窗口统计
        return 1;
    }

    private function getDevicesCountByIp($ip)
    {
        $key = "devices_per_ip:{$ip}";
        $count = Redis::get($key);
        return $count ? intval($count) : 0;
    }

    private function getSimilarDevices($deviceInfo, $fingerprint)
    {
        // 简化的相似设备检测
        // 实际实现中应该基于设备特征计算
        return 0;
    }

    private function checkFingerprintSimilarity($fingerprint)
    {
        // 简化的指纹相似度检查
        // 实际实现中应该基于指纹特征计算
        return 0;
    }

    private function analyzeTimePattern($ip)
    {
        // 简化的时间模式分析
        // 实际实现中应该基于历史数据分析
        return [
            'is_suspicious' => false,
            'pattern' => 'normal',
            'reason' => 'No suspicious pattern detected'
        ];
    }

    private function checkHardwareSimilarity($deviceInfo)
    {
        // 简化的硬件相似度检查
        // 实际实现中应该基于硬件特征计算
        return 0;
    }

    private function getIpLocation($ip)
    {
        // 简化的IP地理位置获取
        // 实际实现中应该使用IP地理位置数据库
        return [
            'country' => 'unknown',
            'timezone' => '0'
        ];
    }

    private function calculateDistance($lat1, $lon1, $lat2, $lon2)
    {
        // 简化的距离计算（Haversine公式）
        $earthRadius = 6371; // 地球半径（公里）
        
        $latDiff = deg2rad($lat2 - $lat1);
        $lonDiff = deg2rad($lon2 - $lon1);
        
        $a = sin($latDiff/2) * sin($latDiff/2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($lonDiff/2) * sin($lonDiff/2);
        
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        
        return $earthRadius * $c;
    }
}